﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Project_1.Models;
using System.Data;
using System.Web.Helpers;
using System.Data.SqlClient;
using System.IO;
using MarkdownDeep;

namespace Project_1.Controllers
{
    public class QuestionController : Controller
    {
        private const string connectionString = "Data Source=(local);Initial Catalog=AnsBook;Integrated Security=SSPI;MultipleActiveResultSets=True";
        AnsBookContext db = new AnsBookContext(connectionString);
        //
        // GET: /Question/

        public ActionResult Index()
        {
            return View();
        }



        public ActionResult CreateQuestion()
        {
            if (Session["Username"] == null)
            {
                TempData["Error"] = "You must log on first";
                TempData["Action"] = "CreateQuestion";
                TempData["Controller"] = "Question"; 
                return RedirectToAction("LogOn", "User");
            }
            else
            {
                List<Category> list = Cate();
                ViewBag.CategoryList = new SelectList(list, "Id", "Name");
                return View();
            }
        }

        [HttpPost]
        public ActionResult CreateQuestion(CreateQuestionModel model, HttpPostedFileBase file, string CaptchaValue, string InvisibleCaptchaValue)
        {
            DateTime thisTime = DateTime.Now;
            bool cv = CaptchaController.IsValidCaptchaValue(CaptchaValue.ToUpper());
            bool icv = String.Compare(InvisibleCaptchaValue, "", false) == 0;
            if (!cv || !icv)
            {
                ModelState.AddModelError(string.Empty, "Captcha error.");
                return View();
            }
            if (ModelState.IsValid)
            {
                List<Category> list = Cate();
                ViewBag.CategoryList = new SelectList(list, "Id", "Name", model.CategoryId);
                Question newQuest = new Question();
                model.Content = model.Content.Replace("\r\n", "<br/>");
                newQuest.Title = model.Title;
                newQuest.Content = model.Content;
                newQuest.CategoryId = model.CategoryId;
                newQuest.CreateTime = thisTime;
                newQuest.UpdateTime = thisTime;
                newQuest.Views = 0;
                newQuest.Username = Session["Username"].ToString();
                if (file != null && file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var path = Path.Combine(Server.MapPath("~/Content/uploads"), fileName);
                    file.SaveAs(path);
                }
                db.Entry(newQuest).State = EntityState.Added;
                db.SaveChanges();
                Follow fl = new Follow();
                fl.QuestionId = newQuest.Id;
                fl.Username = Session["Username"].ToString();
                db.Entry(fl).State = EntityState.Added;
                db.SaveChanges();
                return RedirectToAction("ViewQuestion", "Question", new { id = newQuest.Id });
            }
            return RedirectToAction("Index", "Home");

        }

        public ActionResult ViewQuestion(string id)
        {
            Question temp = new Question();
            temp = db.Questions.Find(int.Parse(id));
            if (temp != null)
            {
                // Instantiate
                var md = new Markdown();
                // Set options
                md.ExtraMode = true;
                // Translate
                temp.Content = md.Transform(temp.Content);
                ViewBag.Question = temp;
                Category cate = db.Categories.Find(temp.CategoryId);
                ViewBag.Category = cate;
                Session["PostId"] = temp.Id;
                if (Session["Username"] != null)
                {
                    Follow fl = db.Follows.Find(Session["Username"].ToString(), int.Parse(id));
                    if (fl != null)
                    {
                        ViewBag.Followed = true;
                    }
                    else
                    {
                        ViewBag.Followed = false;
                    }
                }
            }
            else
            {
                ViewBag.Error = "Question Not Found";
            }
            return View();
        }

        public ActionResult Follow(string id)
        {

            Follow fl = db.Follows.Find(Session["Username"].ToString(), int.Parse(id));
            if (fl != null)
            {
                db.Follows.Remove(fl);
                db.SaveChanges();
                return RedirectToAction("ViewQuestion", "Question", new { id = id });
            }
            else
            {
                Follow fll = new Follow() { QuestionId = int.Parse(id), Username = Session["Username"].ToString() };
                db.Entry(fll).State = EntityState.Added;
                db.SaveChanges();
                return RedirectToAction("ViewQuestion", "Question", new { id = id });
            }
        }



        private List<Category> Cate()
        {
            var list = new List<Category>();
            int tier = 0;
            var listFirst = db.Categories.Where(u => u.ParentId == 0);
            if (listFirst!=null)
            {
                foreach (var item in listFirst)
                {
                    list.Add(new Category(item.Id, item.Name));
                    SubCate(item.Id, ref tier, ref list);
                }
            }
            
            return list;
        }

        private void SubCate(int parentId, ref int tier, ref List<Category> list)
        {
            tier++;
            int first = tier;
            string ttt = null;
            for (int i = 0; i < tier; i++)
            {
                ttt += "--";
            }
            var listTest = db.Categories.Where( u => u.ParentId == parentId );
            if (listTest!=null)
            {
                foreach (var item in listTest)
                {
                    list.Add(new Category(item.Id, ttt + item.Name));
                    SubCate(item.Id, ref tier, ref list);
                    tier = first--;
                }
            }
            
        }

    }
}
